//
//  ChiaInfoTableViewController.m
//  ITHome
//
//  Created by lanou3g on 15/7/15.
//  Copyright (c) 2015年 YAX. All rights reserved.
//

#import "ChiaInfoTableViewController.h"
#import "HeaderWebViewController.h"

#define kCInfo @"ChinaInfoTable"          //国内资讯

@interface ChiaInfoTableViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *chinaInfoModelArray; //国内资讯model数组
@property (nonatomic, assign) int page; // 上下拉刷新的数据个数
@property (nonatomic, strong) UITableView *tableView; //tableView


@end

@implementation ChiaInfoTableViewController

#pragma mark - 懒加载
- (NSMutableArray *)chiaInfoModelArray
{
    if (!_chinaInfoModelArray)
    {
        _chinaInfoModelArray = [[NSMutableArray alloc] init];
        self.page = 1;
    }
    return _chinaInfoModelArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 进来自动刷新
    [self downRefresh];
    
    [self createTableView];
    
    // 上下拉刷新
    [self refresh];
}

#pragma mark - 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 30 - 64 - 49) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_tableView];
}

#pragma mark - 数据刷新
- (void)refresh
{
    // 下拉刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    
    // 上拉刷新
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
}

#pragma mark - 下拉刷新
- (void)downRefresh
{
    
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    // 如果有网
    if ([r currentReachabilityStatus] != NotReachable)
    {
        [FMDBManage deleteAllDatabaseTable:kCInfo];   //刷新成功后再移除数据库中数据。
    }
    else
    {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭, 请检查网络"];
    }
    // 重新解析
    [self chiaInfoGetAsynchronousRequest];
}

#pragma mark - 上拉刷新
- (void)upRefresh
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    // 如果有网
    if ([r currentReachabilityStatus] != NotReachable)
    {
        // 数据解析
        [self chiaInfoUpGetAsynchronousRequest];
    }
    else
    {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭,请检查网络"];
        // 停止刷新
        [self.tableView.footer endRefreshing];
    }

}


#pragma mark - Table view data source
#pragma mark - 设置每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.chiaInfoModelArray.count;
}

#pragma mark - 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    [tableView registerClass:[ITHomePublicTableViewCell class] forCellReuseIdentifier:cellIdentifier];
    ITHomePublicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    ITHomePublicModel *itHomePublicModel = self.chiaInfoModelArray[indexPath.row];
    [cell loadCellWithDataModel:itHomePublicModel];
    
    return cell;
}


#pragma mark - 数据解析
- (void)chiaInfoGetAsynchronousRequest
{
    [FMDBManage createDatabaseTabel:kCInfo];
    NSArray *arr = [FMDBManage selectAllDatabaseTable:kCInfo];
    if (arr.count != 0)
    {
        self.chinaInfoModelArray = [arr mutableCopy];
    }
    else
    {
        [LORequestManger GET:kChinaInfoUrl success:^(id response) {
            [self.chinaInfoModelArray removeAllObjects];
            NSDictionary *bigDictionary = (NSDictionary *)response;
            NSDictionary *smallDictionary = [bigDictionary objectForKey:@"data"];
            NSArray *chinaInfoArray = [smallDictionary objectForKey:@"feeds"];
            for (NSDictionary *chinaInfoDictionary in chinaInfoArray)
            {
                ITHomePublicModel *itHomePubicModel = [ITHomePublicModel itHomePubicModelWithDictionary:chinaInfoDictionary];
                
                //插入数据库（离线用）
                [FMDBManage insertCacheTable:kCInfo Title:itHomePubicModel.title created_at:itHomePubicModel.created_at replies_count:itHomePubicModel.replies_count featureImageUrl:itHomePubicModel.feature_img];
                
                [self.chinaInfoModelArray addObject:itHomePubicModel];
            }
            [self.tableView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [ProgressHUD progressHUD:self.view labelText:@"加载失败,请检查网络"];
        }];
    }
    // 停止刷新
    [self.tableView.header endRefreshing];
}

#pragma mark - 上拉刷新解析
- (void)chiaInfoUpGetAsynchronousRequest
{
    // 获取数组中的最后一个model
    ITHomePublicModel *itHomePubliac = self.chinaInfoModelArray[_chinaInfoModelArray.count - 1];
    self.page +=1; // 页数加1
    
    // 拼接URL
    NSString *stringUrl = [NSString stringWithFormat:@"http://rong.36kr.com/api/v1/news?category=us-startups&last_id=%@&page=%d&request_type=1&uid=146261", itHomePubliac.feed_id,_page];

    // 异步解析
    [LORequestManger GET:stringUrl success:^(id response) {
        NSDictionary *bigDictionary = (NSDictionary *)response;
        NSDictionary *smallDictionary = [bigDictionary objectForKey:@"data"];
        NSArray *chinaProjectArray = [smallDictionary objectForKey:@"feeds"];
        for (NSDictionary *chinaProjectDictionary in chinaProjectArray)
        {
            ITHomePublicModel *itHomePubicModel = [ITHomePublicModel itHomePubicModelWithDictionary:chinaProjectDictionary];
            
            [self.chinaInfoModelArray addObject:itHomePubicModel];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败,请检查网络"];
    }];
    // 停止刷新
    [self.tableView.footer endRefreshing];
}

#pragma mark - 设置cell大小
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kScreenIp6(90);
}

#pragma mark - 点击cell触发方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ITHomePublicModel *model = self.chinaInfoModelArray[indexPath.row];
    HeaderWebViewController *web = [[HeaderWebViewController alloc]init];
    web.urlString = [NSString stringWithFormat:@"http://rong.36kr.com/api/v1/news/%@",model.ID];
    web.urlId = [NSString stringWithFormat:@"%@",model.ID]; //id 拼接
    web.commentsCount = [NSString stringWithFormat:@"%@",model.replies_count]; // 评论
    web.url = [NSString stringWithFormat:@"http://36kr.com/p/%@.html", model.ID]; // 分享的Url
    web.feature_img = model.feature_img;
    
    // 模态过去
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:web];
    nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - 内容警告提示
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];
}


@end
